/* 
 * File:   JServerWorker.cpp
 * Author: johnneyshi
 * 
 * Created on 2013年1月27日, 下午8:07
 */

#include <string.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <pthread.h>
#include "JServerWorker.h"
#include "JWorkerThread.h"
#include "JLog.h"
#include <iostream>
#include <boost/property_tree/ptree.hpp>
#include <boost/property_tree/xml_parser.hpp>
#include <boost/foreach.hpp>

using namespace std;

pthread_mutex_t JServerWorker::adapterConnFdMutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t JServerWorker::adapterConnFdCond = PTHREAD_COND_INITIALIZER;

JServerWorker::JServerWorker()
{
    workerArg.currentWorkCount = 0;
}

JServerWorker::JServerWorker(const JServerWorker& orig) : JServer(orig)
{
    
}

void JServerWorker::Init(std::string _configFileName)
{
    ReadConfig(_configFileName);
    workerArg.Print();
}

void JServerWorker::Init(std::string _ip, int _port, int _weight, int _threadCount, int _threadMaxCount)
{
    workerArg.ip = _ip;
    workerArg.port = _port;
    workerArg.weight = _weight;
    workerArg.threadCount = _threadCount;
    workerArg.threadMaxCount = _threadMaxCount;
}

void JServerWorker::Start()
{
    MakeThreads(workerArg.threadCount);
    JServer::Start();
}

JServerWorker::~JServerWorker() 
{
    
}
void* ThreadMain(void* arg)
{
    JServerWorker* pWorker = (JServerWorker*)arg;
    JWorkerThread thread(pWorker,true);
    thread.Start();
}

void JServerWorker::MakeThreads(int _threadCount)
{
    pthread_t pid;
    for(int i = 0;i < _threadCount; ++i)
    {
        pthread_create(&pid,NULL,&ThreadMain,(void*)this);
        //JLog::Log(JLogMessage,"Create thread %u\n",pid);
    }
}

void JServerWorker::DealEpollFd(int fd)
{
    JServer::DealEpollFd(fd);
}

void JServerWorker::AddNewThread()
{
    
}

void JServerWorker::DealNewConnfd(int newFd)
{
    JLog::Log(JLogMessage,"DealNewConnFd:%d\n",newFd);
    pthread_mutex_lock(&adapterConnFdMutex);
    needDealFds.push(newFd);
    pthread_cond_signal(&adapterConnFdCond);
    //JLog::Log(JLogMessage,"send signal\n");
    pthread_mutex_unlock(&adapterConnFdMutex);
}

int JServerWorker::GetWeight()
{
    return this->workerArg.weight;
}

int JServerWorker::GetCurrentWorkCount()
{
    return this->currentWorkCount;
}

void JServerWorker::ReadConfig(std::string _configFileName)
{
    using boost::property_tree::ptree;
    using namespace boost::property_tree::xml_parser;
    ptree pt;
    read_xml(_configFileName, pt);
    workerArg.ip = pt.get<std::string>("ServerWorker.Server.IP");
    workerArg.port = pt.get<int>("ServerWorker.Server.Port");
    JServer::Init(workerArg.ip,workerArg.port);
    
    workerArg.weight = pt.get<int>("ServerWorker.Weight");
    workerArg.threadCount = pt.get<int>("ServerWorker.ThreadCount");
    workerArg.threadMaxCount = pt.get<int>("ServerWorker.ThreadMaxCount");
}
